package cn.tedu.jdbc.Demo;

import cn.tedu.jdbc.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @author Justin Parker
 * @author 2024/8/1 下午10:28
 * @version 1.0
 */
/** 注册类 */
public class eRollDemo {

    public static void eRoll(){
        //加载数据库驱动并创建数据库链接对象
        try(Connection connection = DBUtil.getConnection()) {
            //接收用户输入的信息
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入用户名：");
            String username = scanner.nextLine();
            System.out.println("请输入密码：");
            String password = scanner.nextLine();
            System.out.println("请输入昵称：");
            String nickname = scanner.nextLine();
            System.out.println("请输入年龄：");
            Integer age = scanner.nextInt();
            //创建预编译的SQL语句
            String sql1 ="insert into userinfo(username,password,nickname,age) values(?,?,?,?)";
            String sql2 ="select id from userinfo where username =?";
            //创建预编译SQL语句的对象
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            //设置？的值
            ps2.setString(1,username);
            //执行预编译SQL语句（查询）
            ResultSet resultSet = ps2.executeQuery();
            if (resultSet.next()){
                System.out.println("用户名已存在,注册失败");
            }else {
                ps1.setString(1,username);
                ps1.setString(2,password);
                ps1.setString(3,nickname);
                ps1.setInt(4,age);
                //执行预编译SQL语句（添加）
                int i = ps1.executeUpdate();
                if (i>0){
                    System.out.println("注册成功");
                }else {
                    System.out.println("注册失败");
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

